package com.kunpeng.weibo.tencent.api;

import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Bundle;
import android.util.Log;
import android.webkit.SslErrorHandler;
import android.webkit.URLUtil;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.kunpeng.weibo.tencent.TencentWeibo;
import com.kunpeng.weibo.tencent.beans.OAuth;
import com.kunpeng.weibo.tencent.utils.AuthorizeInterface;
import com.kunpeng.weibo.tencent.utils.OAuthClient;
import com.kunpeng.weibo.tencent.utils.Utils;

/**
 * 认证相关接口
 * 
 * @author Lee
 * @date 2012-4-23
 * @Description TODO
 */
public class Authorize_API {

	private WebView				mWebView;

	private AuthorizeInterface	mAuthorizeInterface;

	/**
	 * 认证
	 * 
	 * @param webview 打开认证页面的WebView
	 * @param authorizeInterface 认证的回调接口
	 */
	public void authorize(WebView webview, AuthorizeInterface authorizeInterface) {
		String url = "";
		if (webview == null) {
			throw new NullPointerException();
		}
		mWebView = webview;
		mAuthorizeInterface = authorizeInterface;
		setWebViewClient();

		OAuthClient oauthClient = new OAuthClient();
		OAuth oauth;
		try {
			oauth = oauthClient.requestToken(TencentWeibo.getInstance().getOAuth());
			TencentWeibo.getInstance().setOAuth(oauth);
			if (oauth.getStatus() == 0) {
				String oauthToken = oauth.getOauth_token();
				url = "http://open.t.qq.com/cgi-bin/authorize?oauth_token=" + oauthToken;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (URLUtil.isHttpUrl(url) || URLUtil.isHttpsUrl(url)) {
			mWebView.loadUrl(url);
		} else {
			if (mAuthorizeInterface != null) {
				mAuthorizeInterface.authorizeFailed("获取认证URL错误");
			}
		}
	}

	private void setWebViewClient() {
		mWebView.getSettings().setJavaScriptEnabled(true);
		mWebView.getSettings().setDefaultTextEncodingName("utf-8");
		mWebView.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				//待后台增加对默认重定向地址的支持后修改下面的逻辑
				Log.i("lijinzhe", "shouldOverrideUrlLoading  url:" + url);
				if (url.startsWith(TencentWeibo.REDIRECT_URI_CALLBACK)) {
					view.stopLoading();
					Bundle values = Utils.parseTencentUrl(url);

					String error = values.getString("error");
					String error_code = values.getString("error_code");

					if (error == null && error_code == null) {
						String oauth_token = values.getString("oauth_token");
						String oauth_verifier = values.getString("oauth_verifier");
						TencentWeibo.getInstance().getOAuth().setOauth_verifier(oauth_verifier);
						TencentWeibo.getInstance().getOAuth().setOauth_token(oauth_token);

						try {
							TencentWeibo.getInstance().setOAuth(new OAuthClient().accessToken(TencentWeibo.getInstance().getOAuth()));
						} catch (Exception e) {
							e.printStackTrace();
						}

						if (TencentWeibo.getInstance().getOAuth().getStatus() == 2) {
							if (mAuthorizeInterface != null) {
								mAuthorizeInterface.authorizeFailed("获取AccessToken失败");
							}
						} else {
							//授权成功
							if (mAuthorizeInterface != null) {
								mAuthorizeInterface.authorizeSuccessful(TencentWeibo.getInstance().getOAuth());
							}
						}
					} else {
						// 用户或授权服务器拒绝授予数据访问权限
						if (mAuthorizeInterface != null) {
							mAuthorizeInterface.authorizeFailed("授权失败");
						}
					}
					return true;
				}
				view.loadUrl(url);
				return true;
			}

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				Log.i("lijinzhe", "onPageStarted   url:" + url);
				super.onPageStarted(view, url, favicon);
			}

			@Override
			public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
				Log.i("lijinzhe", "onReceivedError   url:" + failingUrl);
				if (mAuthorizeInterface != null) {
					mAuthorizeInterface.authorizeFailed(description);
				}
				super.onReceivedError(view, errorCode, description, failingUrl);
			}

			@Override
			public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
				handler.proceed();
			}
		});
	}
}
